package org.altervista.cp.microkernel;

import java.io.File;
import java.io.FilenameFilter;

import org.altervista.cp.microkernel.io.WorkingDirectory;

class WorkingDirectoryImpl implements WorkingDirectory {

	public Directory getDirectory() {
		return _workingDir;
	}

	public Directory getLogDirectory() {
		if (_logDir == null) {
			_logDir = new Directory(_workingDir.getPath() + "/log");
		}
		return _logDir;
	}

	public Directory getTmpDirectory() {
		if (_tmpDir == null) {
			_tmpDir = new Directory(_workingDir.getPath() + "/tmp");

			for (File f : _tmpDir.listFiles(new FilenameFilter() {
				public boolean accept(File dir, String name) {
					return name.endsWith(".tmp");
				}
			})) {
				f.delete();
			}
		}
		return _tmpDir;
	}

	public Directory getRdbmsDirectory() {
		if (_rdbmsDir == null) {
			_rdbmsDir = new Directory(_workingDir.getPath() + "/rdbms");
		}
		return _rdbmsDir;
	}

	public class Directory extends File {
		private static final long serialVersionUID = 1L;

		private Directory(String dirName) {
			super(dirName);
			if (!exists()) {
				if (!mkdirs()) {
					throw new IllegalStateException("Working directory "
							+ getPath() + " cannot be created");
				}
			} else {
				if (!isDirectory()) {
					throw new IllegalStateException("Resource " + getPath()
							+ " is not a directory");
				}
				if (!canRead()) {
					throw new IllegalStateException("Working directory "
							+ getPath() + " cannot be read");
				}
				if (!canWrite()) {
					throw new IllegalStateException("Working directory "
							+ getPath() + " cannot be write");
				}
			}
		}

	}

	WorkingDirectoryImpl() {
		String wdPath = BootstrapProperties.getWorkingDirectoryPath();
		if (wdPath == null) {
			throw new IllegalStateException(
					"No working direcotry path has been configured: cannot start kernel");
		}
		_workingDir = new Directory(wdPath);
		LogContextHandler._LOG_DIRECTORY_PATH = getLogDirectory()
				.getAbsolutePath();
	}

	private Directory _workingDir;
	private Directory _logDir;
	private Directory _rdbmsDir;
	private Directory _tmpDir;

}
